import React, { memo, useState } from "react";

import filterData from "@/assets/data/filter_data.json";
import EntireFilterWrapper from "./style";
import classNames from "classnames";

const EntireFilter = memo(() => {
  // 定义初始化数据
  let [selectData, setSelectData] = useState([]);

  // 过滤单击事件
  function filterClick(item) {
    let newItem = [...selectData];
    // 如果item在newItem里面时，移除
    if (newItem.includes(item)) {
      // findIndex，判断传入值在数组里的那个索引
      let currIndex = newItem.findIndex((findItem) => findItem === item);
      newItem.splice(currIndex, 1);
    } else {
      newItem.push(item);
    }
    setSelectData(newItem);
  }

  return (
    <EntireFilterWrapper>
      <div className="filter-item">
        {filterData.map((item) => {
          return (
            <div
              key={item}
              className={classNames("item", {
                active: selectData.includes(item),
              })}
              onClick={(e) => filterClick(item)}
            >
              {item}
            </div>
          );
        })}
      </div>
    </EntireFilterWrapper>
  );
});

export default EntireFilter;
